package main

import (
	"context"
	"encoding/json"
	"fmt"
	"github.com/gin-contrib/cors"
	"github.com/gin-gonic/gin"
	"github.com/livekit/protocol/auth"
	"github.com/livekit/protocol/livekit"
	lksdk "github.com/livekit/server-sdk-go"
	"net/http"
	"time"
)

var host = "http://127.0.0.1:7880"
var appKey = "devkey"
var appSecret = "secret"


var roomClient = lksdk.NewRoomServiceClient(host, appKey, appSecret)

// 通过房间名称，用户id 生成房间token
func getJoinToken(roomName, identity, CreatRoom string) string {
	at := auth.NewAccessToken(appKey, appSecret)
	grant := &auth.VideoGrant{
		RoomJoin: true,
		Room:     roomName,
	}

	// 逐行调用方法 生成Token
	at.AddGrant(grant)
	at.SetIdentity(identity)
	at.SetValidFor(time.Hour)
	token, _ := at.ToJWT()

	// 当creatRoom 未0 时，创建房间
	if CreatRoom == "0" {
		creatHomeApi(roomName)
	}
	return token
}

// 创建房间
func creatHomeApi(roomName string) {
	room, _ := roomClient.CreateRoom(context.Background(), &livekit.CreateRoomRequest{
		Name:            roomName,
		EmptyTimeout:    10 * 60, // 10 minutes
		MaxParticipants: 20,
	})
	fmt.Printf("房间已创建", room)
}

// 获取房间列表
func getRoomList() string {

	res, err := roomClient.ListRooms(context.Background(), &livekit.ListRoomsRequest{})
	if err != nil {
		fmt.Println("获取房间列表时出错:", err)
		return "[]"
	}
	//转JSON
	jsonData, err := json.Marshal(res)
	if err != nil {
		fmt.Println("转换为JSON时出错:", err)
		return "[]"
	}
	return string(jsonData)
}

// getToken 接收参数的JSON解析
type UserRoom struct {
	// binding:"required"修饰的字段，若接收为空值，则报错，是必须字段
	UserId    string `form:"userId" json:"userId" uri:"userId" xml:"userId" binding:"required"`
	RoomName  string `form:"roomName" json:"roomName" uri:"roomName" xml:"roomName" binding:"required"`
	CreatRoom string `form:"creatRoom" json:"creatRoom" uri:"creatRoom" xml:"creatRoom" binding:"required"`
}

func main() {
	// 1.创建路由
	r := gin.Default()
	// 使用CORS中间件
	r.Use(cors.Default())

	// gin.Context，封装了request和response
	//获取tokenApi
	r.POST("/getToken", func(c *gin.Context) {
		//获取json 参数
		var json UserRoom
		if err := c.ShouldBindJSON(&json); err != nil {
			// 返回错误信息
			// gin.H封装了生成json数据的工具
			c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
			return
		}

		//生成token
		c.JSON(http.StatusOK, getJoinToken(json.RoomName, json.UserId, json.CreatRoom))

	})

	//获取房间列表API
	r.POST("/getRoomList", func(c *gin.Context) {
		c.String(http.StatusOK, getRoomList())

	})
	// 3.监听端口，默认在8080
	// Run("里面不指定端口号默认为8080")
	r.Run(":8000")
}
